// Content Script - 获取网页内容
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'getPageContent') {
        const content = extractPageContent();
        sendResponse({ content: content });
    }
});

// 监听URL变化并通知扩展
(function() {
    let lastUrl = location.href;
    function notifyIfChanged() {
        if (location.href !== lastUrl) {
            lastUrl = location.href;
            chrome.runtime.sendMessage({ action: 'pageUrlChanged', url: location.href });
        }
    }
    window.addEventListener('popstate', notifyIfChanged);
    window.addEventListener('hashchange', notifyIfChanged);
    window.addEventListener('pageshow', notifyIfChanged);
    document.addEventListener('visibilitychange', () => {
        if (!document.hidden) notifyIfChanged();
    });
    setInterval(notifyIfChanged, 1500);
})();

function extractPageContent() {
    // 移除不需要的元素
    const elementsToRemove = [
        'script', 'style', 'nav', 'header', 'footer', 
        'aside', '.advertisement', '.ads', '.sidebar',
        '.comment', '.comments', '.social-share'
    ];
    
    // 创建页面副本
    const pageClone = document.cloneNode(true);
    
    // 移除不需要的元素
    elementsToRemove.forEach(selector => {
        const elements = pageClone.querySelectorAll(selector);
        elements.forEach(el => el.remove());
    });
    
    // 提取主要内容
    let content = '';
    
    // 尝试获取文章内容
    const articleSelectors = [
        'article',
        '[role="main"]',
        '.content',
        '.post-content',
        '.entry-content',
        '.article-content',
        'main'
    ];
    
    let mainContent = null;
    for (const selector of articleSelectors) {
        mainContent = pageClone.querySelector(selector);
        if (mainContent) break;
    }
    
    if (mainContent) {
        content = mainContent.textContent;
    } else {
        // 如果没有找到主要内容区域，使用body内容
        content = pageClone.body.textContent;
    }
    
    // 清理文本
    content = cleanText(content);
    
    return content;
}

function cleanText(text) {
    return text
        // 移除多余的空白字符
        .replace(/\s+/g, ' ')
        // 移除换行符
        .replace(/\n+/g, ' ')
        // 移除制表符
        .replace(/\t+/g, ' ')
        // 移除多余的空格
        .replace(/\s{2,}/g, ' ')
        // 移除首尾空格
        .trim()
        // 限制长度
        .substring(0, 10000);
} 